package com.link.base.base.wechat.service;

import com.link.base.user.model.CoreUser;
import com.link.base.base.coupons.model.Coupons;
import com.link.base.base.coupons.service.CouponsService;
import com.link.base.base.wechat.dao.mybatis.mapper.WxMenuMapper;
import com.link.base.base.wechat.model.AutoReply;
import com.link.base.base.wechat.model.Menu;
import com.link.base.base.wechat.model.WxImage;
import com.link.base.wechat.mpnews.model.Article;
import com.link.base.wechat.wxmenu.model.WxCommonButton;
import com.link.base.wechat.wxmenu.model.WxComplexButton;
import com.link.base.wechat.wxmenu.model.WxMenu;
import com.link.base.wechat.wxmenu.service.WmenuService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信公众号自定义菜单实现类
 *
 * @author lujiang
 * @date 2019/02/26 10:00
 */

@Service
public class WxMenuServiceImpl extends BasicServiceImpl<Menu> implements MenuService {
    @Resource
    private WxMenuMapper wxmenuMapper;
    @Resource
    private WxPlatformService wxPlatformService;

    @Resource
    private AutoReplyService autoReplyService;

    @Resource
    private CouponsService couponsService;
    @Resource
    private WxImageService wxImageService;
    @Resource
    private ArticlesService articlesService;
    @Resource
    private WxTokenService wxTokenService;

    @Resource
    private WmenuService wmenuService;


    @Override
    public BasicMapper<Menu> getBasicMapper() {
        return wxmenuMapper;
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateWxMenu(List<Menu> deletemenu,List<Menu> addmenu) throws Exception {
        for (int i = 0; i < deletemenu.size(); i++) {
            if ("delete".equals(deletemenu.get(i).getRow_status())) {
                deleteById(deletemenu.get(i));
            } else if ("update".equals(deletemenu.get(i).getRow_status())) {
                update(deletemenu.get(i));
            }
        }
        for (int i = 0; i < addmenu.size(); i++) {
            insert(addmenu.get(i));
        }
    }

    @Override
    public Map<String, Object> createWxMenu(List<Menu> menulist) throws Exception {
        Map<String, Object> result = new HashMap<>(16);
        List<Menu> menu = new ArrayList<>();
        menu = menulist;
        if (menulist.size() < 1) {
            throw new ServiceException("WECHAT-016");
        }
        int listmenu1 = menu.size();
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setWx_og_id(String.valueOf(menu.get(0).getWxId()));
        wxPlatform.setLoginCorpId(menu.get(0).getLoginCorpId());
        wxPlatform.setPageFlag(false);
        List<WxPlatform> platformlist = wxPlatformService.queryByExamplePage(wxPlatform);
        WxPlatform platform = new WxPlatform();
        if (platformlist.size() > 0) {
            platform = platformlist.get(0);
        } else {
            throw new ServiceException("WECHAT-017");
        }
        /**
         * 一级菜单中输入文字即代表一级菜单被激活，激活后的一级菜单必须设置二级菜单或者填写对应的图文消息/链接，否则无法保存，
         * 切换到其他记录时报错：‘请设置该一级菜单对应的二级菜单，或者设置一级菜单的内容
         */
        for (int j = 0; j < menu.size(); j++) {
            if (null == menu.get(j).getFmenu()) {
                String text = menu.get(j).getMessage();
                String link = menu.get(j).getLink();
                boolean flagOne = (listmenu1 < 0) ? true : false;
                boolean flagTwo = (text == null || ("").equals(text)) && (link == null || ("").equals(link)) ? true : false;
                if (flagOne && flagTwo) {
                    throw new ServiceException("WECHAT-018");
                }
            }
        }
        if (listmenu1 > 0) {
            // 设置二级菜单
            List<WxCommonButton> commonButtonList = this.setCommonButton(menu);
            // 设置一级菜单
            List<WxComplexButton> complexButtonList1 = this.setComplexButton(menu);
            // 调用接口创建菜单
            int data = wmenuService.upsertWxMenu(platform.getWx_app_id(),this.getMenu(complexButtonList1, commonButtonList));
            // 判断菜单创建结果
            if (1 != data) {
                throw new ServiceException("WECHAT-019");
            }
        }
        return result;
    }

    @Override
    public WxMenu getMenu(List<WxComplexButton> complexButtonList, List<WxCommonButton> commonButtonList) throws Exception {
        for (int i = 0; i < complexButtonList.size(); i++) {
            List<WxCommonButton> commonButtonList1 = new ArrayList<>();
            for (int j = 0; j < commonButtonList.size(); j++) {
                if (complexButtonList.get(i).getName().equals(commonButtonList.get(j).getParentName())) {
                    commonButtonList1.add(commonButtonList.get(j));
                    complexButtonList.get(i).setSubButton(commonButtonList1);
                }
            }
        }
        WxMenu menu = new WxMenu();
        for (int i = 0; i < complexButtonList.size(); i++) {
            menu.setButton(complexButtonList);
        }
        return menu;
    }

    @Override
    public List<WxComplexButton> setComplexButton(List<Menu> list) throws Exception {
        List<WxComplexButton> complexButtons = new ArrayList<>();
        Menu fmenu = new Menu();
        for (int i = 0; i < list.size(); i++) {
            if (("").equals(list.get(i).getFmenu()) || null == list.get(i).getFmenu()) {
                WxComplexButton complexButton = new WxComplexButton();
                fmenu = list.get(i);
                complexButton.setName(fmenu.getMenuName());
                if ("click".equals(fmenu.getMenuType())) {
                    //生成随机数加时间
                    String id = "";
                    //获取当前时间戳
                    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String temp = sf.format(new Date());
                    //获取6位随机数
                    int random = (int) ((Math.random() + 1) * 100000);
                    id = temp + random;
                    complexButton.setKey(id);
                    complexButton.setMediaId(fmenu.getMessage());
                    AutoReply autoReply = new AutoReply();
                    autoReply.setType("click");
                    autoReply.setLoginCorpId(list.get(i).getLoginCorpId());
                    //设置关键字
                    autoReply.setKeyword(id);
                    autoReply.setWxUsername(String.valueOf(fmenu.getWxId()));
                    autoReply.setContentType(fmenu.getMsgType());
                    if (("text").equals(fmenu.getMsgType())) {
                        autoReply.setContent(fmenu.getMessage());
                    } else if (("image").equals(fmenu.getMsgType())) {
                        autoReply.setContent(fmenu.getMessage());
                    } else if (("mpnews").equals(fmenu.getMsgType())) {
                        autoReply.setContent(fmenu.getMessage());
                    } else if (("wxcard").equals(fmenu.getMsgType())) {
                        autoReply.setContent(fmenu.getMessage());
                    }
                    //保存到数据库,用以自动回复
                    autoReplyService.insert(autoReply);
                }
                complexButton.setUrl(fmenu.getLink());
                complexButton.setType(fmenu.getMenuType());
                complexButton.setPagepath(fmenu.getLink());
                complexButtons.add(complexButton);
            }
        }
        return complexButtons;
    }

    @Override
    public List<WxCommonButton> setCommonButton(List<Menu> lis) throws Exception {
        List<WxCommonButton> list = new ArrayList<>();
        Menu smenu = new Menu();
        for (int i = 0; i < lis.size(); i++) {
            smenu = lis.get(i);
            if (!("").equals(lis.get(i).getFmenu()) && null != lis.get(i).getFmenu()) {
                WxCommonButton button = new WxCommonButton();
                button.setName(smenu.getMenuName());
                if ("click".equals(smenu.getMenuType())) {
                    //生成随机数加时间
                    String id = "";
                    //获取当前时间戳
                    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String temp = sf.format(new Date());
                    //获取6位随机数
                    int random = (int) ((Math.random() + 1) * 100000);
                    id = temp + random;
                    button.setKey(id);
                    button.setMediaId(smenu.getMessage());
                    //存储数据库用以自动回复
                    AutoReply autoReply = new AutoReply();
                    autoReply.setType("click");
                    autoReply.setContentType(smenu.getMsgType());
                    autoReply.setLoginCorpId(lis.get(i).getLoginCorpId());
                    //设置关键字
                    autoReply.setKeyword(id);
                    autoReply.setWxUsername(String.valueOf(smenu.getWxId()));
                    if (("text").equals(smenu.getMsgType())) {
                        autoReply.setContent(smenu.getMessage());
                    } else if (("image").equals(smenu.getMsgType())) {
                        autoReply.setContent(smenu.getMessage());
                    } else if (("mpnews").equals(smenu.getMsgType())) {
                        autoReply.setContent(smenu.getMessage());
                    } else if (("wxcard").equals(smenu.getMsgType())) {
                        autoReply.setContent(smenu.getMessage());
                    }
                    //保存到数据库,用以自动回复
                    autoReplyService.insert(autoReply);
                }
                button.setUrl(smenu.getLink());
                button.setType(smenu.getMenuType());
                button.setPagepath(smenu.getLink());
                button.setParentName(smenu.getFmenu());
                button.setMediaId(String.valueOf(smenu.getSourceid()));
                //小程序頁面路徑
                button.setPagepath(smenu.getPagepath());
                button.setAppid(smenu.getAppid());
                list.add(button);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> deleteWxMenu(Long wx_id) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        // 获取微信公众号信息 拿到token
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setId(wx_id);
        WxPlatform platform = wxPlatformService.queryById(wxPlatform);
        int result = wmenuService.clearWxMenu(platform.getWx_app_id());
        // 判断成功或者失败，1：删除数据库数据，0：返回清空失败
        if (result == 1) {
            Menu entity = new Menu();
            entity.setWxId(platform.getWx_og_id());
            entity.setLoginCorpId(UserUtil.getUser().getLoginCorpId());
            entity.setPageFlag(false);
            List<Menu> menus = this.queryByExamplePage(entity);
            for (int i = 0; i < menus.size(); i++) {
                this.deleteById(menus.get(i));
            }
        } else {
            throw new ServiceException("WECHAT-020");
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteSecondWxMenu(List<Menu> menulist) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        List<Menu> menu = new ArrayList<>();
        List<Menu> deletemenu = new ArrayList<>();
        List<Menu> addmenu = new ArrayList<>();
        for (int i = 0; i < menulist.size(); i++) {
            Menu menu2 = menulist.get(i);
            if ("delete".equals(menu2.getRow_status())) {
                deletemenu.add(menu2);
                continue;
            } else if ("update".equals(menu2.getRow_status())) {
                deletemenu.add(menu2);
                menu.add(menu2);
            } else if ("insert".equals(menu2.getRow_status())) {
                addmenu.add(menu2);
                menu.add(menu2);
            } else {
                menu.add(menu2);
            }
            for (int j = 0; j < menu2.getListMenu().size(); j++) {
                Menu menu3 = menu2.getListMenu().get(j);
                if ("delete".equals(menu3.getRow_status())) {
                    deletemenu.add(menu3);
                    continue;
                } else if ("update".equals(menu3.getRow_status())) {
                    deletemenu.add(menu3);
                    menu.add(menu3);
                } else if ("insert".equals(menu3.getRow_status())) {
                    addmenu.add(menu3);
                    menu.add(menu3);
                } else {
                    menu.add(menu3);
                }
            }
        }
        // 重新生成新的菜单
        map = this.createWxMenu(menu);
        // 修改数据库
        this.updateWxMenu(deletemenu,addmenu);
        return map;
    }

    @Override
    public Map<String, Object> queryWxMenu(String wx_id) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        CoreUser user = UserUtil.getUser();
        Menu menu = new Menu();
        menu.setWxId(wx_id);
        menu.setPageFlag(false);
        menu.setLoginCorpId(user.getCorpid());
        List<Menu> list = this.queryByExamplePage(menu);
        for (int i = 0; i < list.size(); i++) {
            Menu querymenu = list.get(i);
            querymenu.setRow_status("exist");
            if ("image".equals(querymenu.getMsgType()) && !StringUtils.isBlank(querymenu.getMessage())) {
                WxImage image = new WxImage();
                image.setLoginCorpId(querymenu.getCorpid());
                image.setThumbMediaId(querymenu.getMessage());
                image.setPageFlag(false);
                List<WxImage> images = wxImageService.queryByExamplePage(image);
                if (images.size() > 0) {
                    querymenu.setWxImage(images.get(0));
                }
            } else if ("mpnews".equals(querymenu.getMsgType()) && !StringUtils.isBlank(querymenu.getMessage())) {
                Article articles = new Article();
                articles.setLoginCorpId(querymenu.getCorpid());
                articles.setMediaId(querymenu.getMessage());
                articles.setPageFlag(false);
                List<Article> articlesList = articlesService.queryByExamplePage(articles);
                if (articlesList.size() > 0) {
                    querymenu.setArticles(articlesList.get(0));
                }
            } else if ("wxcard".equals(querymenu.getMsgType()) && !StringUtils.isBlank(querymenu.getMessage())) {
                Coupons coupons = new Coupons();
                coupons.setLoginCorpId(querymenu.getCorpid());
                coupons.setPageFlag(false);
                coupons.setWeChatCouponId(querymenu.getMessage());
                List<Coupons> coupons2 = couponsService.queryByExamplePage(coupons);
                if (coupons2.size() > 0) {
                    querymenu.setCoupons(coupons2.get(0));
                }
            }
        }
        List<Menu> flist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if ("".equals(list.get(i).getFmenu()) || null == list.get(i).getFmenu()) {
                flist.add(list.get(i));
            }
        }
        for (int i = 0; i < flist.size(); i++) {
            List<Menu> menus = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                if (flist.get(i).getMenuName().equals(list.get(j).getFmenu())) {
                    menus.add(list.get(j));
                }
            }
            flist.get(i).setListMenu(menus);
        }
        map.put("result", flist);
        return map;
    }

    @Override
    public Map<String, Object> deleteMenu(Long[] ids) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        if (null == ids) {
            throw new ServiceException("WECHAT-021");
        }
        for (int i = 0; i < ids.length; i++) {
            Menu menu = this.queryById(ids[i]);
            if (menu == null) {
                continue;
            }
            Menu menu2 = new Menu();
            menu2.setFmenu(menu.getMenuName());
            menu2.setPageFlag(false);
            menu2.setLoginCorpId(menu.getCorpid());
            List<Menu> menus = this.queryByExamplePage(menu2);
            this.deleteById(menu);
            for (int j = 0; j < menus.size(); j++) {
                this.deleteById(menus.get(j));
            }
        }
        return map;
    }
}
